package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.Dept;
import com.evaluation.entity.PositionType;
import com.evaluation.entity.Teacher;
import com.evaluation.entity.TeacherPosition;
import com.evaluation.service.DeptService;
import com.evaluation.service.PositionTypeService;
import com.evaluation.service.TeacherPositionService;
import com.evaluation.service.TeacherService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 岗位管理控制器
 */
@RestController
@RequestMapping("/api/admin/position")
public class AdminPositionController {

    @Autowired
    private PositionTypeService positionTypeService;

    @Autowired
    private TeacherPositionService teacherPositionService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private DeptService deptService;

    // ========== 岗位类型管理 ==========

    /**
     * 分页查询岗位类型列表
     */
    @GetMapping("/type/list")
    public Result getPositionTypeList(@RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer size,
                                      @RequestParam(required = false) String gwmc) {
        try {
            QueryWrapper<PositionType> queryWrapper = new QueryWrapper<>();

            if (gwmc != null && !gwmc.trim().isEmpty()) {
                queryWrapper.like("GWMC", gwmc);
            }

            // 只查询有效岗位
            queryWrapper.eq("GWZT", "0");
            queryWrapper.orderByAsc("GWBH");

            Page<PositionType> pageResult = positionTypeService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询岗位类型列表失败");
        }
    }

    /**
     * 获取所有岗位类型（用于下拉选择）
     */
    @GetMapping("/type/options")
    public Result getPositionTypeOptions() {
        try {
            QueryWrapper<PositionType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("GWZT", "0"); // 只查询有效岗位
            queryWrapper.orderByAsc("GWBH");
            queryWrapper.select("GWBH", "GWMC");

            List<PositionType> positionList = positionTypeService.list(queryWrapper);
            return Result.success(positionList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取岗位类型选项失败");
        }
    }

    /**
     * 根据ID查询岗位类型详情
     */
    @GetMapping("/type/{gwbh}")
    public Result getPositionTypeById(@PathVariable String gwbh) {
        try {
            PositionType positionType = positionTypeService.getById(gwbh);
            if (positionType == null) {
                return Result.error("岗位类型不存在");
            }
            return Result.success(positionType);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询岗位类型详情失败");
        }
    }

    /**
     * 新增岗位类型
     */
    @PostMapping("/type")
    public Result addPositionType(@RequestBody PositionType positionType) {
        try {
            // 验证必填字段
            if (positionType.getGwbh() == null || positionType.getGwbh().trim().isEmpty()) {
                return Result.error("岗位编号不能为空");
            }
            
            if (positionType.getGwmc() == null || positionType.getGwmc().trim().isEmpty()) {
                return Result.error("岗位名称不能为空");
            }
            
            // 检查岗位编号是否已存在
            PositionType existingPosition = positionTypeService.getById(positionType.getGwbh().trim());
            if (existingPosition != null) {
                return Result.error("岗位编号已存在");
            }
            
            // 检查岗位名称是否已存在
            QueryWrapper<PositionType> nameQueryWrapper = new QueryWrapper<>();
            nameQueryWrapper.eq("GWMC", positionType.getGwmc().trim());
            PositionType existingByName = positionTypeService.getOne(nameQueryWrapper);
            if (existingByName != null) {
                return Result.error("岗位名称已存在");
            }
            
            // 设置字段值
            positionType.setGwbh(positionType.getGwbh().trim());
            positionType.setGwmc(positionType.getGwmc().trim());
            
            // 设置默认状态为有效
            if (positionType.getGwzt() == null || positionType.getGwzt().trim().isEmpty()) {
                positionType.setGwzt("0");
            }

            boolean result = positionTypeService.save(positionType);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加岗位类型失败：" + e.getMessage());
        }
    }

    /**
     * 更新岗位类型
     */
    @PutMapping("/type/{gwbh}")
    public Result updatePositionType(@PathVariable String gwbh, @RequestBody PositionType positionType) {
        try {
            positionType.setGwbh(gwbh);
            boolean result = positionTypeService.updateById(positionType);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新岗位类型失败");
        }
    }

    /**
     * 删除岗位类型（逻辑删除）
     */
    @DeleteMapping("/type/{gwbh}")
    public Result deletePositionType(@PathVariable String gwbh) {
        try {
            PositionType positionType = new PositionType();
            positionType.setGwbh(gwbh);
            positionType.setGwzt("1"); // 设置为无效状态

            boolean result = positionTypeService.updateById(positionType);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除岗位类型失败");
        }
    }

    // ========== 教师岗位关系管理 ==========

    /**
     * 分页查询教师岗位关系列表
     */
    @GetMapping("/teacher/list")
    public Result getTeacherPositionList(@RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer size,
                                         @RequestParam(required = false) String jsxm,
                                         @RequestParam(required = false) String gwbh,
                                         @RequestParam(required = false) String bmbh) {
        try {
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();

            if (jsxm != null && !jsxm.trim().isEmpty()) {
                queryWrapper.like("JSXM", jsxm);
            }

            if (gwbh != null && !gwbh.trim().isEmpty()) {
                queryWrapper.eq("GWBH", gwbh);
            }

            if (bmbh != null && !bmbh.trim().isEmpty()) {
                queryWrapper.eq("BMBH", bmbh);
            }

            queryWrapper.orderByAsc("JSBH", "GWBH");

            Page<TeacherPosition> pageResult = teacherPositionService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师岗位关系列表失败");
        }
    }

    /**
     * 根据教师编号查询岗位
     */
    @GetMapping("/teacher/{jsbh}/positions")
    public Result getPositionsByTeacher(@PathVariable String jsbh) {
        try {
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSBH", jsbh);
            queryWrapper.orderByAsc("GWBH");

            List<TeacherPosition> positionList = teacherPositionService.list(queryWrapper);
            return Result.success(positionList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师岗位失败");
        }
    }

    /**
     * 根据岗位编号查询教师
     */
    @GetMapping("/position/{gwbh}/teachers")
    public Result getTeachersByPosition(@PathVariable String gwbh) {
        try {
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("GWBH", gwbh);
            queryWrapper.orderByAsc("JSBH");

            List<TeacherPosition> teacherList = teacherPositionService.list(queryWrapper);
            return Result.success(teacherList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询岗位教师失败");
        }
    }

    /**
     * 新增教师岗位关系
     */
    @PostMapping("/teacher")
    public Result addTeacherPosition(@RequestBody TeacherPosition teacherPosition) {
        try {
            // 检查是否已存在相同的关系
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSBH", teacherPosition.getJsbh());
            queryWrapper.eq("GWBH", teacherPosition.getGwbh());
            queryWrapper.eq("BMBH", teacherPosition.getBmbh());

            TeacherPosition existingRelation = teacherPositionService.getOne(queryWrapper);
            if (existingRelation != null) {
                return Result.error("该教师已具有此岗位");
            }

            boolean result = teacherPositionService.save(teacherPosition);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加教师岗位关系失败");
        }
    }

    /**
     * 根据教师编号、岗位编号、部门编号查询教师岗位关系详情
     */
    @GetMapping("/teacher/{jsbh}/{gwbh}/{bmbh}")
    public Result getTeacherPositionDetail(@PathVariable String jsbh,
                                           @PathVariable String gwbh,
                                           @PathVariable String bmbh) {
        try {
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSBH", jsbh);
            queryWrapper.eq("GWBH", gwbh);
            queryWrapper.eq("BMBH", bmbh);

            TeacherPosition teacherPosition = teacherPositionService.getOne(queryWrapper);
            if (teacherPosition == null) {
                return Result.error("教师岗位关系不存在");
            }
            return Result.success(teacherPosition);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师岗位关系详情失败");
        }
    }

    /**
     * 更新教师岗位关系
     */
    @PutMapping("/teacher/{jsbh}/{gwbh}/{bmbh}")
    public Result updateTeacherPosition(@PathVariable String jsbh,
                                        @PathVariable String gwbh,
                                        @PathVariable String bmbh,
                                        @RequestBody TeacherPosition teacherPosition) {
        try {
            // 设置复合主键
            teacherPosition.setJsbh(jsbh);
            teacherPosition.setGwbh(gwbh);
            teacherPosition.setBmbh(bmbh);

            // 使用条件更新，因为是联合主键
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSBH", jsbh);
            queryWrapper.eq("GWBH", gwbh);
            queryWrapper.eq("BMBH", bmbh);

            boolean result = teacherPositionService.update(teacherPosition, queryWrapper);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新教师岗位关系失败");
        }
    }

    /**
     * 删除教师岗位关系
     */
    @DeleteMapping("/teacher/{jsbh}/{gwbh}/{bmbh}")
    public Result deleteTeacherPosition(@PathVariable String jsbh,
                                        @PathVariable String gwbh,
                                        @PathVariable String bmbh) {
        try {
            // 使用复合主键删除
            QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("JSBH", jsbh);
            queryWrapper.eq("GWBH", gwbh);
            queryWrapper.eq("BMBH", bmbh);

            boolean result = teacherPositionService.remove(queryWrapper);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除教师岗位关系失败");
        }
    }

    /**
     * 批量导入教师岗位关系
     */
    @PostMapping("/teacher/import")
    public Result importTeacherPositions(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 读取Excel文件
            List<TeacherPosition> positionList = ExcelUtil.readExcel(file, TeacherPosition.class);
            
            if (positionList.isEmpty()) {
                return Result.error("Excel文件中没有有效数据");
            }

            int successCount = 0;
            int errorCount = 0;

            for (TeacherPosition position : positionList) {
                try {
                    // 验证必填字段
                    if (position.getJsbh() == null || position.getGwbh() == null) {
                        errorCount++;
                        continue;
                    }

                    // 检查是否已存在相同的关系
                    QueryWrapper<TeacherPosition> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("JSBH", position.getJsbh());
                    queryWrapper.eq("GWBH", position.getGwbh());

                    TeacherPosition existingRelation = teacherPositionService.getOne(queryWrapper);
                    if (existingRelation == null) {
                        teacherPositionService.save(position);
                        successCount++;
                    } else {
                        // 更新现有关系信息
                        if (position.getBmbh() != null) existingRelation.setBmbh(position.getBmbh());
                        if (position.getBmmc() != null) existingRelation.setBmmc(position.getBmmc());
                        if (position.getGwmc() != null) existingRelation.setGwmc(position.getGwmc());
                        if (position.getJsxm() != null) existingRelation.setJsxm(position.getJsxm());
                        
                        teacherPositionService.updateById(existingRelation);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入教师岗位关系失败：" + e.getMessage());
        }
    }

    /**
     * 根据教师编号查询教师信息
     */
    @GetMapping("/teacher/info/{jsbh}")
    public Result getTeacherInfo(@PathVariable String jsbh) {
        try {
            Teacher teacher = teacherService.getById(jsbh);
            if (teacher == null) {
                return Result.error("教师不存在");
            }
            return Result.success(teacher);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询教师信息失败");
        }
    }

    /**
     * 根据岗位编号查询岗位信息
     */
    @GetMapping("/position/info/{gwbh}")
    public Result getPositionInfo(@PathVariable String gwbh) {
        try {
            PositionType position = positionTypeService.getById(gwbh);
            if (position == null) {
                return Result.error("岗位不存在");
            }
            return Result.success(position);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询岗位信息失败");
        }
    }

    /**
     * 根据部门编号查询部门信息
     */
    @GetMapping("/dept/info/{bmbh}")
    public Result getDeptInfo(@PathVariable String bmbh) {
        try {
            Dept dept = deptService.getById(bmbh);
            if (dept == null) {
                return Result.error("部门不存在");
            }
            return Result.success(dept);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门信息失败");
        }
    }

    /**
     * 批量删除教师岗位关系
     */
    @DeleteMapping("/teacher/batch")
    public Result batchDeleteTeacherPositions(@RequestBody List<Integer> ids) {
        try {
            boolean result = teacherPositionService.removeByIds(ids);
            if (result) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除教师岗位关系失败");
        }
    }

    /**
     * 导入岗位类型数据
     */
    @PostMapping("/type/import")
    public Result importPositionTypes(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            List<PositionType> positions = ExcelUtil.readExcel(file, PositionType.class);

            if (positions.isEmpty()) {
                return Result.error("文件中没有有效数据");
            }

            // 批量保存
            boolean success = positionTypeService.saveBatch(positions);

            if (success) {
                return Result.success("导入成功，共导入" + positions.size() + "条数据");
            } else {
                return Result.error("导入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导出岗位类型数据
     */
    @GetMapping("/type/export")
    public void exportPositionTypes(HttpServletResponse response,
                                    @RequestParam(required = false) String gwmc) {
        try {
            QueryWrapper<PositionType> queryWrapper = new QueryWrapper<>();

            if (gwmc != null && !gwmc.trim().isEmpty()) {
                queryWrapper.like("GWMC", gwmc);
            }

            queryWrapper.eq("GWZT", "0");
            queryWrapper.orderByAsc("GWBH");

            List<PositionType> positions = positionTypeService.list(queryWrapper);

            String[] headers = {"岗位编号", "岗位名称", "岗位类型", "状态"};
            String[] fields = {"gwbh", "gwmc", "gwlx", "gwzt"};
            String fileName = "岗位数据_" + System.currentTimeMillis() + ".xlsx";

            ExcelUtil.writeExcel(response, positions, headers, fields, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载教师岗位导入模板
     */
    @GetMapping("/teacher/template/download")
    public void downloadTeacherPositionTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据
            List<Map<String, Object>> templateData = new ArrayList<>();
            
            // 添加示例数据
            Map<String, Object> example1 = new HashMap<>();
            example1.put("教师编号", "10001");
            example1.put("教师姓名", "张三");
            example1.put("岗位编号", "20");
            example1.put("岗位名称", "管理人员");
            example1.put("部门编号", "11103");
            example1.put("部门名称", "网络信息部");
            templateData.add(example1);

            Map<String, Object> example2 = new HashMap<>();
            example2.put("教师编号", "10002");
            example2.put("教师姓名", "李四");
            example2.put("岗位编号", "21");
            example2.put("岗位名称", "专任教师");
            example2.put("部门编号", "11200");
            example2.put("部门名称", "计算机学院");
            templateData.add(example2);

            Map<String, Object> example3 = new HashMap<>();
            example3.put("教师编号", "10003");
            example3.put("教师姓名", "王五");
            example3.put("岗位编号", "24");
            example3.put("岗位名称", "辅导员");
            example3.put("部门编号", "11202");
            example3.put("部门名称", "信息工程学院");
            templateData.add(example3);
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "教师岗位导入模板", templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
